package com.handydata.antifraud.rule.funcs;

import com.handydata.antifraud.enums.RuleNonQuntityValueConvertEnum;
import com.handydata.antifraud.to.RiskInputTO;
import com.handydata.antifraud.to.RiskMiddleTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 计算单位名称相似度
 */
@Component
public class CalcUnitNameSimilarity extends CalculateAdapter {
    /**相似度临界值*/
    private static final double SIMILARITY_CRITICAL_VALUE = 0.5;
    private static final Logger logger = LoggerFactory.getLogger(CalcUnitNameSimilarity.class);
    @Override
    public void doCalc(RiskInputTO riskInputTO, RiskMiddleTO riskMiddleTO) {
        double levenshtein = levenshtein(riskInputTO.getUnitName(), riskInputTO.getLastUnitName());
        if(levenshtein >= SIMILARITY_CRITICAL_VALUE) {
            riskMiddleTO.setCalASbR004DWMCYZ(RuleNonQuntityValueConvertEnum.MATCH_OK.getCode());
        } else {
            riskMiddleTO.setCalASbR004DWMCYZ(RuleNonQuntityValueConvertEnum.MATCH_FAIL.getCode());
        }
    }

    public double levenshtein(String str1,String str2) {
        if(str1==null||str2==null) return 0;
        //计算两个字符串的长度。
        int len1 = str1.length();
        int len2 = str2.length();
        //建立上面说的数组，比字符长度大一个空间
        int[][] dif = new int[len1 + 1][len2 + 1];
        //赋初值，步骤B。
        for (int a = 0; a <= len1; a++) {
            dif[a][0] = a;
        }
        for (int a = 0; a <= len2; a++) {
            dif[0][a] = a;
        }
        //计算两个字符是否一样，计算左上的值
        int temp;
        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
                    temp = 0;
                } else {
                    temp = 1;
                }
                //取三个值中最小的
                dif[i][j] = min(dif[i - 1][j - 1] + temp, dif[i][j - 1] + 1,
                        dif[i - 1][j] + 1);
            }
        }
        logger.info("字符串{}与{}的比较", str1, str2);
        //取数组右下角的值，同样不同位置代表不同字符串的比较
        logger.info("差异步骤：{}", dif[len1][len2]);
        //计算相似度
        double similarity = 1 - (double) dif[len1][len2] / Math.max(str1.length(), str2.length());
        logger.info("相似度:" + similarity);
        return similarity;
    }

    //得到最小值
    private static int min(int... is) {
        int min = Integer.MAX_VALUE;
        for (int i : is) {
            if (min > i) {
                min = i;
            }
        }
        return min;
    }

//    public static void main(String[] args) {
//        CalcUnitNameSimilarity s = new CalcUnitNameSimilarity();
//        s.levenshtein("中国民生银行投资", "中民投");
//    }
}
